<!--
 * @description  : 实地核查方位图-添加位置-标距页面
 * @create       : 2024-7-30
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"> </theme-navbar>
    <!-- #endif -->
    <view class="m-content">
      <view class="gauge-tabs">
        <view class="gauge-tab" :style="{ color: item.value === curGaugeType ? '#fff' : '#333' }" v-for="item in gauges" :key="item.index" @click="handleGaugeChange(item.value)"
          >{{ item.label }}标距</view
        >
        <view id="active-bg" class="active-bg"></view>
      </view>
      <view class="tips" v-if="curGaugeType === 'manual'">请点击“描点”绘制测量轨迹，完成后点“标距”标注距离</view>
      <mapAddLocation ref="mapAddLocation" :location="location" :entityList="entityList" :curGaugeType="curGaugeType"></mapAddLocation>
      <view class="btns">
        <u-button class="btn back" type="primary" @click="goBack">
          返回
        </u-button>
        <u-button class="btn" type="primary" @click="confirm">
          确定
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import mapAddLocation from "./mapAddLocation.vue";
import { screenshots } from "@/common/ScreenshotsUtil.js";
import certificateService from "@/service/certificate/certificate.service.js";

export default {
  onLoad(opt) {
    this.location = opt.curLocation.split(",");
    this.entityList = this.$storage.get("checkedEntityList");
  },
  components: {
    mapAddLocation
  },
  data() {
    return {
      location: [],
      entityList: [],
      gauges: [
        {
          label: "步行导航",
          value: "walk"
        },
        {
          label: "人工",
          value: "manual"
        }
      ],
      curGaugeType: "walk"
    };
  },
  methods: {
    // 切换标距类型
    async handleGaugeChange(value) {
      this.curGaugeType = value;
      const element = document.getElementById("active-bg");
      const offset = value === "walk" ? "0" : "100";
      element.style.transform = `translateX(${offset}%)`;
      element.style.transition = "all 0.35s ease 0s";
      await this.$nextTick();
      this.$refs.mapAddLocation.gaugeChangeCallback(value);
    },
    confirm() {
      const _this = this;
      uni.showModal({
        title: "提示",
        content: "实地核查会用到商户位置截图，请问是否需要截图？",
        success: async function(res) {
          if (!res.confirm) return;
          // 实地核查TODO 调保存接口保存当前周边零售户|学校数据
          const { fieldAuditUuid, handleMainUuid } = _this.$storage.get("curConfirmInfo");
          const list = _this.entityList.map(item => {
            const { type, bizUUid, name, longitude, latitude, walkDistance, manualDistance, licNo } = item;
            const info = {
              fieldAuditUuid,
              handleMainUuid,
              longitude,
              latitude,
              regionType: type,
              regionUuid: bizUUid,
              regionName: name,
              distance: +walkDistance,
              actualDistance: +manualDistance
            };
            if (type === "01") {
              info.regionCode = licNo;
            }
            return info;
          });
          _this.$u.loading("保存中...");
          try {
            const response = await certificateService.saveFieldAuditLayout(list);
            _this.$u.hideLoading();
            if (response.success) {
              // 截图并上传
              const screenshotUrl = await _this.getUrlFromScreenShots();
              if (screenshotUrl) {
                const location = {
                  longitude: _this.location[0],
                  latitude: _this.location[1]
                };
                let param = Object.assign(location, { imgData: screenshotUrl, isScreenshot: true });
                _this.backPrev(
                  {
                    paramKey: "pos",
                    param
                  },
                  3
                );
              }
              // 清空缓存数据
              _this.$storage.remove("curConfirmInfo");
              _this.$storage.remove("checkedEntityList");
            } else {
              uni.showToast({
                title: "保存失败！",
                icon: "none"
              });
            }
          } catch (err) {
            _this.$u.hideLoading();
            console.log(err);
          }
        }
      });
    },
    // 当前选址位置截图生成方位图url
    async getUrlFromScreenShots() {
      // 当前选址位置截图处理，生成经营场所方位图
      let screenshotUrl = "";
      const canvasBox = document.querySelector("#container") || null;
      const scrollTop = document.documentElement.scrollTop;
      // 左侧计算方法， 元素距离屏幕左侧的距离
      const canvasBoxOffsetLeft = canvasBox ? canvasBox.getBoundingClientRect().left : 0;
      // 顶部计算方法， 元素距离顶部距离 + body滚动高度
      const canvasBoxOffsetTop = canvasBox ? canvasBox.offsetTop + scrollTop : 0;
      try {
        // await接收图片地址
        screenshotUrl = await screenshots({
          canvasBox,
          canvasBoxOffsetLeft,
          canvasBoxOffsetTop
        });
      } catch (err) {
        console.log("err", err);
      }
      return screenshotUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

.page {
  padding: 0;
}

#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}
.m-content {
  position: relative;
}
.gauge-tabs {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  display: flex;
  width: calc(100% - 40rpx);
  height: 68rpx;
  line-height: 68rpx;
  background-color: #ffffff;
  font-weight: bold;
  z-index: 99;
  border-radius: 10rpx;
  box-shadow: #e5e5e5 5px 10px 15px;
  .gauge-tab {
    width: 50%;
    text-align: center;
    transition: all 0.35s;
  }
  .active-bg {
    position: absolute;
    background-color: #0070d2;
    border-radius: 10rpx;
    height: 68rpx;
    width: 50%;
    z-index: -1;
  }
}

.tips {
  position: absolute;
  top: 110rpx;
  z-index: 999;
  color: #d20000;
  background-color: #ffffff;
  padding: 16rpx 22rpx;
}

.btns {
  display: flex;
  background-color: #ffffff;
  position: fixed;
  bottom: 0px;
  left: 0;
  right: 0;
  z-index: 999;
  .btn {
    margin: 30rpx;
    width: 50%;
  }
  .back {
    border: 1px solid #0070d2;
    color: #0070d2;
    background-color: #ffffff;
  }
}
/deep/.u-btn {
  height: 63rpx;
  line-height: 63rpx;
  border-radius: 8rpx;
}
.u-size-default {
  font-size: 28rpx;
}
</style>
